package cn.com.redis;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;
/**
 * Redis配置信息的初始化工具
 * @author Hardin Xu
 *
 */
public class RedisInitializer {
	public static ShardedJedisPool shardedJedisPool = null;
	
	static {
		ResourceBundle bundle = RedisInitializer.getResourceBundle();
		
		JedisPoolConfig config = RedisInitializer.getJedisConfig(bundle);
		
		//redis.hosts.shards， redis集群服务器ip组，用,隔开
		String hostsStr = bundle.getString("redis.hosts.shards");
		//redis.ports.shards，服务器对应的redis端口组
		String portsStr = bundle.getString("redis.ports.shards");
		
		String passwordsStr = bundle.getString("redis.passwords.shards");
		
		String[] redisHosts = hostsStr.split(",");
		
		String[] sRedisPorts = portsStr.split(",");
		
		String[] redisPasswords = passwordsStr.split(",");
		
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		
		for (int i=0; i<redisHosts.length; i++) {
			JedisShardInfo jedisShard = new JedisShardInfo(redisHosts[i], Integer.parseInt(sRedisPorts[i]));
			jedisShard.setPassword(redisPasswords[i]);
			shards.add(jedisShard);
		}
		
		synchronized(RedisInitializer.class) {
			RedisInitializer.shardedJedisPool = new ShardedJedisPool(config, shards);	
		}
		
	}
	
	/**
	 * 获得jedis配置，配置文件应该位于具体web项目下的resources文件夹下，命名为redis.properties
	 * @return
	 */
	private static ResourceBundle getResourceBundle(){
		ResourceBundle bundle = ResourceBundle.getBundle("redis", Locale.ENGLISH);
		if (bundle == null) {
			throw new IllegalArgumentException(
				"[redis.properties] is not found!");
		}
		return bundle;
	}
	
	/**
	 * 设置jedis连接池的参数，
	 * 其中redis.pool.maxActive表示连接池运行同时产生的最大连接数，可以在调试时根据负载均衡能力进行优化
	 * redis.pool.maxIdle表示最大空闲进程数，用来提高并发能力
	 * redis.pool.maxWait连接池超时时间
	 * @param bundle
	 * @return
	 */
	private static JedisPoolConfig getJedisConfig(ResourceBundle bundle) {
		JedisPoolConfig config = new JedisPoolConfig();
		
		config.setMaxTotal(Integer.valueOf(bundle
			.getString("redis.pool.maxActive")));
		config.setMaxIdle(Integer.valueOf(bundle
			.getString("redis.pool.maxIdle")));
		config.setMaxWaitMillis(Long.valueOf(bundle
			.getString("redis.pool.maxWait")));	
		
		return config;
	}
	
}
